/**Trigger Name: NMROpportunityAmountUpdate 
 * Author: Accenture
 * Requirement/Project Name: NMR
 * Requirement Description: Trigger for creation or update of opportunity 
                            for each proposal created in CRM
 */
trigger NMROpportunityAmountUpdate on Proposal_Summary__c (before insert, before update) {

    Map<string,Proposal_Summary__c> proposalMap = new Map<string,Proposal_Summary__c>();
    set<string> csscustidSet = new set<string>();
    set<string> attuidSet = new set<string>();
    
    Map<Id,Double> updateproposalMap = new Map<Id,Double>();
    set<string> opptyId = new set<string>();
        
    for(Proposal_Summary__c propSummary:Trigger.new){
        if(Trigger.ISINSERT){
            if(propSummary.Proposal_Rep_ATTUID__c != NULL && propSummary.Customer_ID__c != NULL){
                string attcssString = propSummary.Proposal_Rep_ATTUID__c.toLowerCase()+propSummary.Customer_ID__c.toLowerCase();
                if(proposalMap.get(attcssString) != NULL){
                    propSummary.addError('A Proposal is present with the same ATTID and Customer Id');
                }
                else{
                    proposalMap.put(attcssString,propSummary);
                    csscustidSet.add(propSummary.Customer_ID__c.toLowerCase());
                    attuidSet.add(propSummary.Proposal_Rep_ATTUID__c.toLowerCase());
                }
            }
        }
        if(Trigger.isUpdate && (propSummary.Proposal_NISD_Amount__c != Trigger.OldMap.get(propSummary.Id).Proposal_NISD_Amount__c)){
            if(propSummary.Opportunity_Id__c != Null){
                updateproposalMap.put(propSummary.Opportunity_Id__c, propSummary.Proposal_NISD_Amount__c );
                opptyId.add(propSummary.Opportunity_id__c);
            }                
        }
    }
    
    if(proposalMap.size()>0){
        NMRCreateUpdateOpptyfromProposal.createOppty(csscustidSet,attuidSet,proposalMap);
    }
    if(updateproposalMap.size()>0){
                NMRCreateUpdateOpptyfromProposal.updateOppty(updateproposalMap, opptyId);
    }
    
}